/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Formularios;

import BD.pedidos;
import BD.pedidos_Itens;
import BD.pizzas;
import BD.produtos;
import BD.sabores;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author CORE
 */
public class SelecionaPedidos_itens extends javax.swing.JDialog {
    public String s = "";
    private Integer id_pedidos = 0;

    public Integer getId_pedidos() {
        return id_pedidos;
    }

    public void setId_pedidos(Integer id_pedidos) {
        this.id_pedidos = id_pedidos;
    }
    /**
     * Creates new form NewJDialog
     */
    public SelecionaPedidos_itens(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        CarregaCombobox();
        setLocationRelativeTo(null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jbtnGravar = new javax.swing.JButton();
        jbtncancelar = new javax.swing.JButton();
        jpnlAbas = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtblPizza = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jcbxsaborPesq = new javax.swing.JComboBox();
        jPanel2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jtblProduto = new javax.swing.JTable();
        jtProduto = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jbtnPesquisa = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Master Pizza - Seleciona Pedidos");

        jbtnGravar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icones/Gravar.png"))); // NOI18N
        jbtnGravar.setText("Selecionar");
        jbtnGravar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnGravarActionPerformed(evt);
            }
        });

        jbtncancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icones/Cancelar.png"))); // NOI18N
        jbtncancelar.setText("Sair");
        jbtncancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtncancelarActionPerformed(evt);
            }
        });

        jpnlAbas.setToolTipText("");

        jtblPizza.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Pizza Sabor", "Tamanho", "Valor"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jtblPizza.setCellSelectionEnabled(true);
        jtblPizza.getTableHeader().setReorderingAllowed(false);
        jtblPizza.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jtblPizzaMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(jtblPizza);
        jtblPizza.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        if (jtblPizza.getColumnModel().getColumnCount() > 0) {
            jtblPizza.getColumnModel().getColumn(0).setMaxWidth(50);
            jtblPizza.getColumnModel().getColumn(1).setMaxWidth(500);
            jtblPizza.getColumnModel().getColumn(2).setMaxWidth(50);
            jtblPizza.getColumnModel().getColumn(3).setMaxWidth(100);
        }

        jLabel1.setText("Pizza");

        jcbxsaborPesq.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jcbxsaborPesq.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jcbxsaborPesqActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(0, 392, Short.MAX_VALUE))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addComponent(jcbxsaborPesq, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jcbxsaborPesq, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 193, Short.MAX_VALUE)
                .addContainerGap())
        );

        jpnlAbas.addTab("                        Pizzas                        ", jPanel1);

        jLabel2.setText("Produtos");

        jtblProduto.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Produto", "Volume", "Valor"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jtblProduto.setCellSelectionEnabled(true);
        jtblProduto.getTableHeader().setReorderingAllowed(false);
        jtblProduto.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jtblProdutoMouseClicked(evt);
            }
        });
        jScrollPane3.setViewportView(jtblProduto);
        jtblProduto.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        if (jtblProduto.getColumnModel().getColumnCount() > 0) {
            jtblProduto.getColumnModel().getColumn(0).setMaxWidth(50);
            jtblProduto.getColumnModel().getColumn(1).setMaxWidth(500);
            jtblProduto.getColumnModel().getColumn(2).setMaxWidth(50);
            jtblProduto.getColumnModel().getColumn(3).setMaxWidth(100);
        }

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 416, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jtProduto))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jtProduto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(11, 11, 11)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 193, Short.MAX_VALUE)
                .addContainerGap())
        );

        jpnlAbas.addTab("               Bebidas                    ", jPanel2);

        jLabel3.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
        jLabel3.setText("Seleção de itens do pedido");

        jbtnPesquisa.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icones/Pesquisa.png"))); // NOI18N
        jbtnPesquisa.setText("Pesquisar");
        jbtnPesquisa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnPesquisaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(130, 130, 130)
                .addComponent(jLabel3)
                .addContainerGap(234, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jpnlAbas, javax.swing.GroupLayout.PREFERRED_SIZE, 441, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jbtnPesquisa, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jbtncancelar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbtnGravar, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(101, 101, 101)
                        .addComponent(jbtnPesquisa)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jbtnGravar)
                        .addGap(11, 11, 11)
                        .addComponent(jbtncancelar))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jpnlAbas)))
                .addGap(9, 9, 9))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void preenchepizza(ArrayList<pizzas> ls){
      DefaultTableModel modeloTabela = (DefaultTableModel)jtblPizza.getModel();                
      
      while(jtblPizza.getRowCount()>0 ){
          modeloTabela.removeRow(0);               
      }        
      for(int i = 0; i < ls.size();i++){      
          modeloTabela.addRow(new String[ modeloTabela.getColumnCount() ]);        
          jtblPizza.setValueAt(ls.get(i).getId_pizzas(), i, 0);
          jtblPizza.setValueAt(ls.get(i).getDesc_sabor(), i, 1);
          jtblPizza.setValueAt(ls.get(i).getTamanho(), i,2 );
          jtblPizza.setValueAt(ls.get(i).getValor(), i, 3);        
      }           
    }
    private void preencheprodutos(ArrayList<produtos> ls){
      DefaultTableModel modeloTabela = (DefaultTableModel)jtblProduto.getModel();                
      
      while(jtblProduto.getRowCount()>0 ){
          modeloTabela.removeRow(0);               
      }        
      for(int i = 0; i < ls.size();i++){      
          modeloTabela.addRow(new String[ modeloTabela.getColumnCount() ]);        
          jtblProduto.setValueAt(ls.get(i).getId_produtos(), i, 0);
          jtblProduto.setValueAt(ls.get(i).getDescricao(), i, 1);
          jtblProduto.setValueAt(ls.get(i).getVolume(), i,2 );
          jtblProduto.setValueAt( ls.get(i).getCusto(), i, 3);        
      }           
    }
    
    private void jbtnPesquisaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnPesquisaActionPerformed
      if(jpnlAbas.getSelectedIndex() == 0) {
          pizzas pz = new pizzas();
          if(jcbxsaborPesq.getSelectedIndex()>=0)
              pz.setDesc_sabor(jcbxsaborPesq.getSelectedItem().toString());
          else
              pz.setDesc_sabor("");        
          ArrayList<pizzas> ls = new ArrayList<pizzas>();
          ls = pz.getItens();      
          preenchepizza(ls);
      }
      else
      {
         produtos prd = new produtos() ;
         prd.setIngrediente(false);
         prd.pesp_ingredi = true;
         if(! jtProduto.getText().equals(""))
             prd.setDescricao(jtProduto.getText());
         else
             prd.setDescricao("");
         
         ArrayList<produtos> lsprd = new ArrayList<produtos>();
         lsprd = prd.getItens();
         preencheprodutos(lsprd);
      }    
    }//GEN-LAST:event_jbtnPesquisaActionPerformed

    private void jbtnGravarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnGravarActionPerformed
        if(jpnlAbas.getSelectedIndex() == 0) {
            if(jtblPizza.getSelectedRow() < 0)
                JOptionPane.showMessageDialog(rootPane, "Favor selecione uma pizza");            
            else    
            {           
                //checa se existe igredientes
                pizzas pg = new pizzas();
                pg.setId_pizzas(jtblPizza.getValueAt(jtblPizza.getSelectedRow(), 0).hashCode());
                String s = pg.checapizzaigre();
                if(s != ""){
                    JOptionPane.showMessageDialog(rootPane, s);
                    return;
                }
                    
                
                pedidos_Itens ped = new pedidos_Itens();
                ped.setId_pedidos(this.getId_pedidos());
                ped.setId_pizzas(jtblPizza.getValueAt(jtblPizza.getSelectedRow(), 0).hashCode());
                ped.setValor(Float.parseFloat(jtblPizza.getValueAt(jtblPizza.getSelectedRow(),3).toString()));
                
                if (ped.incluir()) {
                      JOptionPane.showMessageDialog(null, "Operação bem sucedida");

                } else {
                      JOptionPane.showMessageDialog(null, "Erro ao incluir pizza");
                }
            }    
        }
        else
        {
            if(jtblProduto.getSelectedRow() < 0)
                JOptionPane.showMessageDialog(rootPane, "Favor selecione um Produto");            
            else    
            {           
                pedidos_Itens ped = new pedidos_Itens();
                produtos prod = new produtos();
                ArrayList<produtos> lstprod = new ArrayList<produtos>();
                prod.setId_produtos(jtblProduto.getValueAt(jtblProduto.getSelectedRow(), 0).hashCode());
                lstprod = prod.getItens();
                
                ped.setId_pedidos(this.getId_pedidos());
                ped.setId_produtos(lstprod.get(0).getId_produtos());
                ped.setProdutos(lstprod.get(0));
                ped.setValor(Float.parseFloat(jtblProduto.getValueAt(jtblProduto.getSelectedRow(),3).toString()));
                if (ped.incluir()) {
                        JOptionPane.showMessageDialog(null, "Operação bem sucedida");
                    } else {
                        JOptionPane.showMessageDialog(null, "Erro ao incluir produtos");
                    }
            }    
        }    
  
    }//GEN-LAST:event_jbtnGravarActionPerformed

    private void jbtncancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtncancelarActionPerformed
        this.dispose();
        
        jpnlAbas.setSelectedIndex(1);
    }//GEN-LAST:event_jbtncancelarActionPerformed

    private void jtblPizzaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtblPizzaMouseClicked
        // TODO add your handling code here:
        if(evt.getClickCount() == 2)
            jbtnGravarActionPerformed(null);
    }//GEN-LAST:event_jtblPizzaMouseClicked

    private void jtblProdutoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtblProdutoMouseClicked
        // TODO add your handling code here:
        if(evt.getClickCount()==2)
            jbtnGravarActionPerformed(null);
    }//GEN-LAST:event_jtblProdutoMouseClicked

    private void jcbxsaborPesqActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcbxsaborPesqActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jcbxsaborPesqActionPerformed
    
    private void CarregaCombobox() {
        sabores sab = new sabores();        
        jcbxsaborPesq.removeAllItems();

        ArrayList<sabores> listsa = new ArrayList<sabores>() ;
        listsa = sab.getItens();
        
        for (int i = 0; i < listsa.size(); i++) {
            jcbxsaborPesq.addItem(listsa.get(i).getDescricao());

        }
        jcbxsaborPesq.setSelectedIndex(-1);       
    }

    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SelecionaPedidos_itens.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SelecionaPedidos_itens.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SelecionaPedidos_itens.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SelecionaPedidos_itens.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                SelecionaPedidos_itens dialog = new SelecionaPedidos_itens(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JButton jbtnGravar;
    private javax.swing.JButton jbtnPesquisa;
    private javax.swing.JButton jbtncancelar;
    private javax.swing.JComboBox jcbxsaborPesq;
    private javax.swing.JTabbedPane jpnlAbas;
    private javax.swing.JTextField jtProduto;
    private javax.swing.JTable jtblPizza;
    private javax.swing.JTable jtblProduto;
    // End of variables declaration//GEN-END:variables
}
